<template>
	<view class="px-2 py-4">
		<form-component :formFields="formFields" :formData="formData" :formRules="formRules" :fileLists="fileLists"
			:startUserSelectTasks="visibleUserSelectTasks" :startUserSelectAssignees="visibleUserSelectAssignees"
			:startUserSelectAssigneesFormRules="startUserSelectAssigneesFormRules" :detailId="detailId"
			:resubmit="resubmit" @submitForm="submitForm" @cancelForm="cancelForm" />

	</view>
</template>

<script setup lang="ts">
import {
	onLoad
} from "@dcloudio/uni-app";
import { ref, reactive, nextTick, computed, watch } from 'vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { buildFileList } from '@/utils/fileUtils'
import { getAccessToken } from '@/utils/auth'
import * as DefinitionApi from '@/api/bpm/definition'
import { getUserProfile, getUserSalary } from "@/api/system/user/profile";
import * as UserApi from '@/api/system/user/index'
import { SealManagerApi, SealManagerVO } from '@/api/oa/sealmanager'
import { useMessage, useToast } from 'wot-design-uni'


const message = useMessage()
const toast = useToast()
const globalConfig = (getApp() as any).globalData.config;
const detailId = ref(null)
const resubmit = ref(0)
const fileList = ref([]) // 文件列表
const userList = ref<any[]>([])
const data = ref({ path: '' })
const headerObj = ref(
	{
		Authorization: 'Bearer ' + getAccessToken()
	}
)

// 指定审批人
const processDefineKey = ref<string>('oa_sealbase')
const startUserSelectTasks = ref<any>([]) // 发起人需要选择审批人的用户任务列表
const startUserSelectAssignees = ref<any>({}) // 发起人选择审批人的数据
const startUserSelectAssigneesFormRef = ref() // 发起人选择审批人的表单 Ref
const startUserSelectAssigneesFormRules = ref<any>({}) // 发起人选择审批人的表单 Rules
const sealList = ref<any[]>([])
// 独立文件存储（按字段名存储）
const fileLists = ref<Record<string, any[]>>({
	attachment: []
})
/** 处理级别类型变更 */
const handleDeptTypeChange = async ({ value }: { value: number }) => {
	// 根据类型切换流程定义key
	startUserSelectTasks.value = []
	startUserSelectAssignees.value = {}
	if (value === undefined || value === null) return
	try {
		// 根据不同类型获取不同的流程定义Key
		processDefineKey.value = value === 0 ? 'oa_sealbase' : 'oa_sealenterprise'
		const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
			undefined,
			processDefineKey.value
		)
		if (!processDefinitionDetail) {
			toast.error('流程模型未配置，请检查！')
			return
		}
		startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks
		console.log('startUserSelectTasks.value', startUserSelectTasks.value);
		// 设置指定审批人
		if (startUserSelectTasks.value?.length > 0) {
			// 设置校验规则
			for (const userTask of startUserSelectTasks.value) {
				startUserSelectAssignees.value[userTask.id] = []
				startUserSelectAssigneesFormRules.value[userTask.id] = [
					{
						required: true,
						message: '请选择审批人',
						validator: (value: any) => {
							if (value && Array.isArray(value) && value.length > 0) {
								return Promise.resolve();
							} else {
								return Promise.reject('审批人不能为空');
							}
						},
						trigger: ['change']

					}
				]
			}
		}
	} catch (error) {
		console.error('获取流程定义失败', error)
		toast.error('获取流程定义失败，请重试')
	}
}
// 计算属性：过滤需要显示的审批人任务
const visibleUserSelectTasks = computed(() => {
	if (!startUserSelectTasks.value || startUserSelectTasks.value.length === 0) {
		return []
	}
	if (formData.value.deptType === 0 && formData.value.directorConsulted === '1') {
		return startUserSelectTasks.value.filter((task: any) =>
			task.name !== '分管领导'
		)
		// const Selectted = startUserSelectTasks.value.find(item => item.name == '分管领导')
		// Selectted

	}
	return startUserSelectTasks.value
})
const visibleUserSelectAssignees = computed(() => {
	if (!startUserSelectTasks.value || startUserSelectTasks.value.length === 0) {
		return []
	}
	if (formData.value.deptType === 0 && formData.value.directorConsulted === '1') {
		const Selectted = startUserSelectTasks.value.find((item: any) => item.name == '分管领导')
		if (Selectted && Selectted.id) {
			startUserSelectAssignees.value[Selectted.id] = [1]
		}
	}
	return startUserSelectAssignees.value
})

//表单项字段配置
const formFields = ref<any[]>([
	{
		type: 'radio',
		prop: 'deptType',
		label: '级别类型',
		required: true,
		inline: true,
		options: [
			{ label: '本部', value: 0 },
			{ label: '二级企业', value: 1 }
		],
		optionLabel: 'label',
		optionValue: 'value',
		onChange: handleDeptTypeChange
	},
	{
		type: 'input',
		prop: 'fileName',
		label: '文件名称',
		placeholder: '请输入文件名称'
	},
	{
		type: 'checkbox',
		prop: 'sealId',
		label: '印章名称',
		multiple: true,
		width: '80px',
		options: () => sealList.value, // 动态数据，确保 sealList 格式为 [{ id, sealName }]
		optionLabel: 'sealName',
		optionValue: 'id',
		inline: true,
	},
	{
		type: 'input',
		prop: 'applicantName',
		label: '申请人',
		placeholder: '请输入申请人',
		readonly: true,
	},
	{
		type: 'input',
		prop: 'applicationDept',
		label: '申请部门',
		placeholder: '请输入申请部门',
		readonly: true
	},
	{
		type: 'textarea',
		prop: 'reason',
		label: '事由',
		placeholder: '请输入用印事由'
	},
	{
		type: 'input',
		prop: 'submitDept',
		label: '报送部门',
		placeholder: '请输入报送部门'
	},
	{
		type: 'upload', prop: 'attachment', label: '附件', placeholder: '请输入附件',
		action: globalConfig.uploadUrl,
		limit: 1,
		accept: 'all',
		header: headerObj.value,
		targetMapping: {         // 字段映射配置
			fileUrl: 'attachment',    // 接口返回ID -> formData.serverIds
			fileName: 'ename'     // 文件名 -> formData.fileName
		}
	},
	{
		type: 'radio',
		prop: 'directorConsulted',
		label: '是否请示主管领导',
		width: 150,
		visible: (formData: any) => formData.deptType === 0,
		rules: [
			{ required: true, message: '是否请示主管领导', trigger: 'change' }
		],
		options: [
			{ label: '是', value: '0' },
			{ label: '否', value: '1' }
		],
		optionLabel: 'label',
		optionValue: 'value',
		inline: true,
	},
	{
		type: 'textarea',
		prop: 'remark',
		label: '备注',
		placeholder: '请输入备注'
	}
])//表单项字段配置
const formData = ref<SealManagerVO>({
	deptType: 0,
	directorConsulted: '1'
} as any)

const formRules = reactive({
	deptType: [
		{ required: true, message: '请选择级别类型', trigger: 'blur' }
	],
	fileName: [
		{ required: true, message: '请输入文件名称', trigger: 'blur' }
	],
	sealId: [
		{ required: true, message: '请选择印章', trigger: 'change' }
	],
	applicantName: [
		{ required: true, message: '请选择申请人', trigger: 'change' }
	],
	applicationDept: [
		{ required: true, message: '请选择申请部门', trigger: 'change' }
	],
	submitDept: [
		{ required: true, message: '请输入报送部门', trigger: 'change' }
	],
	reason: [
		{ required: true, message: '请输入事由', trigger: 'blur' }
	],
})

/** 获取用户列表 */
const getUserList = async () => {
	try {
		userList.value = await UserApi.getSimpleUserList();
	} catch (error) {
		console.error("获取用户列表失败:", error);
		userList.value = []; // 失败时，防止 userOptions.value 变成 undefined
	}
}
onLoad(async (options) => {
	console.log('options', options);
	
	const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
		undefined,
		processDefineKey.value
	)
	if (!processDefinitionDetail) {
		toast.error('流程模型未配置，请检查！')
		return
	}
	startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks
	console.log('startUserSelectTasks', processDefinitionDetail)
	// 设置指定审批人
	if (startUserSelectTasks.value?.length > 0) {
		// 设置校验规则
		for (const userTask of startUserSelectTasks.value) {
			startUserSelectAssignees.value[userTask.id] = []
			startUserSelectAssigneesFormRules.value[userTask.id] = [
				{

					required: true,
					message: '请选择审批人',
					validator: (value: any) => {
						console.log("当前审批人值435435:", value); // 调试输出
						if (value && Array.isArray(value) && value.length > 0) {
							console.log('value.length', value.length);
							return Promise.resolve();
						} else {
							return Promise.reject('审批人不能为空');
						}
					},
					trigger: ['change']

				}
			]
		}
		console.log('startUserSelectAssignees.value', startUserSelectAssignees.value);
		console.log('startUserSelectAssigneesFormRules.value', startUserSelectAssigneesFormRules.value);
	}
	detailId.value = options?.id
	resubmit.value = options?.resubmit
	await getUserList()
	/** 获得详情 */
	if (detailId.value) { await getDetailById() }
	const userProfile: any = await getUserProfile()

	formData.value.applicantId = userProfile.id
	formData.value.applicantName = userProfile.nickname
	formData.value.applicationDept = userProfile.dept.name
	/** 获取印章列表 */
	await getSealList()

})


/** 获取页面详情 */
const getDetailById = async () => {
	try {
		const data = await SealManagerApi.getSealManager(Number(detailId.value))
		formData.value = data
		if (formData.value.sealId) {
			const ids = String(formData.value.sealId).split(',').map(id => Number(id.trim()))
			formData.value.sealId = ids
		}
		if (formData.value.deptType) {
			handleDeptTypeChange({ value: formData.value.deptType })
			// console.log('formData.value.applicantId', formData.value.applicantId);
			// console.log('userList.value', userList.value);

			// const selected = userList.value.find(item => item.id === formData.value.applicantId)
			// console.log('selected', selected);

			// formData.value.applicantName = selected.nickname
		}
	} catch (error) {
		console.log('加载数据失败')
	}
}

const getSealList = async () => {
	// 获取印章列表
	try {
		const params = { pageNo: 1, pageSize: 100 }
		const result = await SealManagerApi.getSealList(params)
		sealList.value = result.list || []
		console.log('sealList.value', sealList.value);


	} catch (error) {
		toast.error('获取印章列表失败')
	}
}
/** 提交表单 */
const submitForm = async (payload: any) => {
	const { type, data } = payload
	// ✅ 如果 sealId 是数组则转成字符串
	if (Array.isArray(data.sealId)) {
		data.sealId = data.sealId.join(',')
	}
	try {
		if (type === 'update') {
			await SealManagerApi.updateSealManager(data)
			toast.success('编辑成功');
		} else {
			await SealManagerApi.createSealManager(data)
			toast.success('新增成功');
		}
		// 成功后跳转
		uni.navigateTo({ url: '/pagesPackage/OAsystemAutomation/sealmanager/index' });
	} catch (error) {
		console.error('表单提交失败:', error);
		toast.error('提交失败，请稍后再试');
	}
}

/** 取消表单 */
const cancelForm = async () => {
	try {
		// 删除的二次确认
		await message.confirm({
			msg: '您确定要取消吗？',
			title: '提示'  // 添加标题
		})
		uni.navigateTo({ url: '/pagesPackage/OAsystemAutomation/sealmanager/index' });
		// 显示成功提示
		toast.success('取消成功')
	} catch (error) {
		console.log('用户取消了操作或发生错误:', error)
	}
}
</script>

<style scoped lang="scss">
.container {
	padding: 20px 5px;
}

.custom-shadow {
	width: 40%;
	border-radius: 5%;
}
</style>